package auth_ctrl

import (
	"admin-system/internal/request"
	"admin-system/internal/service/auth_svc"
	"admin-system/pkg/error_code"
	"admin-system/pkg/response"
	"github.com/gin-gonic/gin"
	"strconv"
)

type PermissionController struct {
	PermissionService *auth_svc.PermissionService
}

func NewPermissionController(permissionService *auth_svc.PermissionService) *PermissionController {
	return &PermissionController{
		PermissionService: permissionService,
	}
}

// 权限管理
// GetPermissionList
// @Summary 获取角色权限
// @Description 获取角色权限
// @Method GET
// @Param role_id query int false "角色ID（选填）"
// @Success 200 {object} response.Response{data=[]auth_model.Permission} "获取角色权限成功"
// @Failure 400 {object} response.Response{data=string} "获取角色权限失败"
// @Router /permission/role/{role_id} [get]
func (p *PermissionController) GetPermissionList(c *gin.Context) {
	var roleId *int64 = nil
	// 获取Get请求参数
	roleIdStr := c.Param("role_id")
	// 存在roleId则查询当前角色下的权限列表、否则查询所有的权限列表（后台权限列表渲染）
	if roleIdStr != "" {
		getRoleId, err := strconv.ParseInt(roleIdStr, 10, 64)
		if err != nil {
			response.Fail(c, error_code.ErrInvalidParams, "参数错误")
			return
		}
		roleId = &getRoleId
	}
	// 根据角色ID查询角色下的权限
	permissions, err := p.PermissionService.GetPermission(c, roleId)
	if err != nil {
		response.Fail(c, error_code.ErrNoPermission, "获取权限失败")
	}
	response.Success(c, permissions)
	return
}

// SavePermission
// @Summary 新增权限
func (p *PermissionController) SavePermission(c *gin.Context) {
	var permissionReq request.PermissionRequest
	// 绑定 请求参数
	err := c.ShouldBindJSON(&permissionReq)
	if err != nil {
		response.Fail(c, error_code.ErrInvalidParams, "请求参数错误"+err.Error())
		return
	}
	// 数据落库
	permission, err := p.PermissionService.SavePermission(c, permissionReq)
	if err != nil {
		response.Fail(c, error_code.ErrInternalServer, "创建权限失败"+err.Error())
		return
	}
	response.Success(c, permission)
	return
}

// DelPermission
// @Summary 删除权限
func (p *PermissionController) DelPermission(c *gin.Context) {
	// 获取权限ID
	permissionId := c.Param("id")
	permissionIdInt, err := strconv.ParseInt(permissionId, 10, 64)
	if err != nil {
		response.Fail(c, error_code.ErrInvalidParams, "参数错误")
		return
	}
	// 数据落库
	err = p.PermissionService.DelPermission(c, permissionIdInt)
	if err != nil {
		response.Fail(c, error_code.ErrInternalServer, "删除权限失败"+err.Error())
	}
	response.Success(c, "success")
	return
}
